<template>
    <div class="boxs">
        <el-card>
            <div class="flex_between">
                <div></div>
                <el-button type="primary" icon="el-icon-upload" size="small"
                    @click="handleUpload">{{ $t("translation.upload") }}</el-button>
            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" align="center" width="60" type="index" />
                <el-table-column :label="$t('translation.packageName')" align="center" prop="package_name" />
                <el-table-column :label="$t('translation.version') " align="center" prop="version" />
                <el-table-column :label="$t('translation.translatestate')" align="center" prop="content">
                    <template slot-scope="scope">
                        <el-tag type="danger" v-if="scope.row.flag == '0'">{{ $t('translation.stateNo') }}</el-tag>

                        <el-tag type="success" v-if="scope.row.flag == '1'">{{ $t('translation.stateYes') }}</el-tag>
                        <el-tag type="warning" v-if="scope.row.flag == '2'">{{ $t('translation.Translating') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('translation.submitstatus')" align="center" prop="content">
                    <template slot-scope="scope">
                        <el-tag type="danger"
                            v-if="scope.row.submit_status == '0'">{{ $t('translation.statusNo') }}</el-tag>

                        <el-tag type="success"
                            v-if="scope.row.submit_status == '1'">{{ $t('translation.statusYes') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('translation.updateTime')" align="center" prop="update_time" />

                <el-table-column :label="$t('translation.Operator')" align="center" fixed="right" width="180">
                    <template slot-scope="scope">
                        <el-button size="mini" v-hasRole="['primary']"
                            @click="handleEdit(scope.$index, scope.row)">{{ $t('translation.Edit') }}</el-button>
                        <el-button v-hasRole="['middle']" :disabled="scope.row.submit_status == '0'" size="mini"
                            @click="downloadXMLHandel(scope.$index, scope.row)">{{ $t('translation.Download') }}</el-button>
                    </template>

                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
        </el-card>

        <el-dialog :title="$t('upload.upload')" :visible.sync="dialogVisible" width="800px">
            <el-form class="demo-form-inline" label-width="80px" :model="form" :rules="rules" ref="ruleForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="$t('upload.file')" prop="file">
                            <el-upload class="upload-demo" drag limit="1"
                                action="https://jsonplaceholder.typicode.com/posts/" multiple
                                :http-request="uploadHandel" :on-remove="remeveFile" ref="upload">
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">
                                    {{ $t("upload.uploadText")
                  }}<em> {{ $t("upload.uploadText1") }}</em>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{
                        $t("tagsView.close")
                    }}</el-button>
                <el-button type="warning" :loading="addLoading" @click="affirm">{{
                        $t("table.confirm")
                    }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { uploadXML, getFileList, downloadXML } from "@/api/translate";
import { findUploadPckageList, upload } from "@/api/uploadPackage";
import axios from "@/utils/axios";
import { downloadByUrl } from "@/utils/download";
import pk from "@/utils/pk";
export default {
    name: "uploadList",
    data() {
        return {
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                type: "",
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                description: "",
                file: "",
            },
            search: "",
            rules: {
                description: [
                    { required: true, message: "请输入描述", trigger: "blur" },
                ],
                file: [{ required: true, message: "请上传文件", trigger: "blur" }],
            },
            value1: "",
            packageName: ''
        };
    },
    created() {
        //获取当前路由
        this.packageName = this.extractedString
        this.getMore(this.extractedString)

    },
    computed: {
        currentPath() {
            return this.$route.path;
        },
        extractedString() {
            return this.getSubstringAfter(this.currentPath, "uploadList-");
        },
    },
    methods: {
        getSubstringAfter(str, delimiter) {
            const index = str.indexOf(delimiter);
            if (index !== -1) {
                return str.substring(index + delimiter.length);
            } else {
                return ""; // 如果没有找到分隔符，返回空字符串
            }
        },
        uploadHandel(e) {
            this.form.file = e.file;
        },
        remeveFile() {
            this.form.file = "";
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore(pk) {
            this.loading = true;
            let { data, total } = await getFileList({ packageName: pk });
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        async affirm() {
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                let loading;
                try {
                    let data = new FormData();
                    data.append("xmlFile", this.form.file); // 假设file是你的文件对象
                    data.append("packageName", this.packageName);
                    loading = this.$loading({
                        lock: true,
                        text: "Loading",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)",
                    });
                    this.addLoading = true;
                    let data1 = await uploadXML(data);
                    if (data1.code == 0) {
                        this.addLoading = false;
                        this.$message.success("操作成功");
                        this.getMore(this.packageName);
                        this.dialogVisible = false;
                        this.form.description = "";
                        this.form.file = "";
                    } else {
                        this.$message.error(data1.msg);
                    }
                } catch (e) {
                    this.addLoading = false;
                } finally {
                    this.form.description = "";
                    this.form.file = "";
                    loading.close();
                    this.addLoading = false;
                    if (this.$refs.upload) {
                        this.$refs.upload.clearFiles(); // 清除文件列表
                    }
                }
            });
        },
        openDialog() {
            this.form = {};
            this.dialogVisible = true;
        },
        async downloadXMLHandel(i, row) {
            const { version, package_name } = row;
            const query = {
                package_name: package_name,
                version: version,
            };

            const url = "https://insdoss.freeapptools.com/node/translate/downloadXML";
            const success = await downloadByUrl({
                url: url,
                data: query,
                fileName: `${package_name}-${version}.zip`
            });

            if (success) {
                console.log("File downloaded successfully");
            } else {
                console.error("Error downloading the file");
            }

        },

        handleEdit(i, row) {
            this.$router.push({
                path: `/translation/childTaskList-${this.packageName}`,
                query: { version: row.version },
            });
        },
        handleUpload(i, row) {
            this.form.description = "";
            this.form.file = "";
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles(); // 清除文件列表
            }
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
            }).then(async () => {
                await deleteTemplateType({ id: row.id });
                this.getMore();
                this.$message({
                    message: "删除成功！",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.state = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.getMore();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-upload {
    width: 100% !important;
}

::v-deep .el-upload-dragger {
    width: 100% !important;
}
</style>